package com.yunchao.library.socket.model.security

import com.yunchao.library.socket.extensions.putString
import com.yunchao.library.socket.utils.BufferPool
import com.yunchao.library.socket.utils.EncryptUtils
import java.nio.ByteBuffer

data class AlgorithmData(
    val id: Int,
    val fragment: Int,
    val timestamp: Long,
    val data: String,
    val operator: Int,
    val auditor: Int
) {
    companion object {
        private val UTF8 = Charsets.UTF_8
    }

    /**
    * 将对象转换为字节数组并进行SHA-1加密
    *
    * @return 20字节的SHA-1哈希结果
    * @throws IllegalArgumentException 如果数据转换失败
    */
    fun toByteArray(): ByteArray {
        return try {
            val dataBytes = data.toByteArray(UTF8)
            val bufferSize = calculateBufferSize(dataBytes.size)

            val rawBytes = BufferPool.use(bufferSize) { buffer ->
                buffer. writeToBuffer( data)
                buffer.array().copyOf(buffer.position())
            }

            EncryptUtils.encryptSHA1(rawBytes).also {
                require(it.size == 20) {
                    "SHA-1结果长度异常: 预期20字节，实际${it.size}字节"
                }
            }
        } catch (e: Exception) {
            throw IllegalArgumentException("转换为字节数组失败", e)
        }
    }

    /** 计算所需缓冲区大小 */
    private fun calculateBufferSize(dataLength: Int): Int {
        return Int.SIZE_BYTES * 4 +  // id, fragment, operator, auditor
                Long.SIZE_BYTES +     // timestamp
                Int.SIZE_BYTES +      // data长度字段
                dataLength            // 实际数据
    }

    /** 将数据写入缓冲区 */
    private fun ByteBuffer.writeToBuffer(dataBytes: String) {
        putInt(id)
        putInt(fragment)
        putLong(timestamp)
        putString(dataBytes)
        putInt(operator)
        putInt(auditor)
    }
}